package common;

import java.rmi.RemoteException;
import java.rmi.registry.Registry;

public class RegistryManagement {
	public static Registry createIfNotExists()
	{
		StringBuilder registryHost = new StringBuilder(); 
		StringBuilder registryPortStr = new StringBuilder(); 
		getRegistryInfo(registryHost, registryPortStr);
		int registryPort = Integer.valueOf(registryPortStr.toString());

		Registry registry = null;
		try {
			registry = java.rmi.registry.LocateRegistry.createRegistry(registryPort);
		} 
		catch (NumberFormatException e) {
			System.err.println(e.getMessage());
		} 
		catch (RemoteException e) {
			try {
				registry = java.rmi.registry.LocateRegistry.getRegistry(registryHost.toString(), registryPort);
			} 
			catch (Exception e1) {
			}
		}

		return registry;
	}
	
	public static void getRegistryInfo(StringBuilder registryHost, StringBuilder registryPort)
	{
		java.io.InputStream is = ClassLoader.getSystemResourceAsStream("registry.properties");
		if (is != null) 
		{
			java.util.Properties props = new java.util.Properties();
			try 
			{
				props.load(is);
				registryHost.append(props.getProperty("registry.host"));
				registryPort.append(props.getProperty("registry.port").trim());
				
				is.close();
			}
			catch (Exception e) {
				System.out.println(e.getMessage());
			}
		}
		else 
		{
			System.out.println("Properties file not found!");
		}	

	}
}
